import {Component, OnInit} from '@angular/core';
import {AppContextService} from "../../service/app-context.service";
import {FileModifyService} from "../../service/file-modify.service";
import {PathService} from "../../service/path.service";
import {Observable} from "rxjs";
import {Result} from "../../model/restful";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-view-context-menu',
  templateUrl: './view-context-menu.component.html',
  styleUrls: ['./view-context-menu.component.css']
})
export class ViewContextMenuComponent implements OnInit {

  isCreateFile = false
  createModalTitle = ''
  createModalVisible = false

  filename: string = ''

  constructor(
    private ctx: AppContextService,
    private pathService: PathService,
    private fileModifyService: FileModifyService,
    private messageService: NzMessageService
  ) { }

  ngOnInit(): void {
  }

  doUpload(isFile: boolean) {
    this.ctx.doUploadFile(isFile)
  }

  openCreateFileModal() {
    this.createModalVisible = true
    this.isCreateFile = true
    this.createModalTitle = '新建文件'
  }

  openCreateDirModal() {
    this.createModalVisible = true
    this.isCreateFile = false
    this.createModalTitle = '新建文件夹'
  }

  submitCreateInfo() {
    const observable = this.receiveCreateResponse()
    const ref = this
    observable.subscribe({
      next(r) {
        if (r.success) {
          ref.createModalVisible = false
          ref.messageService.success('创建成功')
        } else {
          ref.handleCreateFileError(r.message, true)
        }
      },
      error(e) {
         ref.handleCreateFileError(e, false)
      }
    })
  }

  cancelCreateModal() {
    this.createModalVisible = false
  }

  doCreate() {

  }

  private handleCreateFileError(message: string, show: boolean) {
    console.log(message)
    if (show) {
      this.messageService.error(message)
    }
  }

  private receiveCreateResponse(): Observable<Result<any>> {
    const path = this.pathService.getFileUrl()
    const fName = this.filename
    if (this.isCreateFile) {
      return this.fileModifyService.createFile(path, fName)
    } else {
      return this.fileModifyService.createDir(path, fName)
    }
  }
}
